package comm.util;

import java.security.*;

   import javax.crypto.*;
   import javax.crypto.spec.*;
import java.io.*;

   /**
   * This program generates a AES key, retrieves its raw bytes, and
   * then reinstantiates a AES key from the key bytes.
   * The reinstantiated key is used to initialize a AES cipher for
   * encryption and decryption.
   */
   
   
   public class AES {

     /**
     * Turns array of bytes into string
     *
     * @param buf	Array of bytes to convert to hex string
     * @return	Generated hex string
     */
     public static String asHex (byte buf[]) {
      StringBuffer strbuf = new StringBuffer(buf.length * 2);
      int i;

      for (i = 0; i < buf.length; i++) {
       if (((int) buf[i] & 0xff) < 0x10)
	    strbuf.append("0");

       strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
      }

      return strbuf.toString();
     }
     
     public static byte[] fromString(String hex) {
 		int len = hex.length();
 		byte[] buf = new byte[((len + 1) / 2)];

 		int i = 0, j = 0;
 		if ((len % 2) == 1)
 			buf[j++] = (byte) fromDigit(hex.charAt(i++));

 		while (i < len) {
 			buf[j++] = (byte) ((fromDigit(hex.charAt(i++)) << 4) | fromDigit(hex
 					.charAt(i++)));
 		}
 		return buf;
 	}
     
     public static int fromDigit(char ch) {
 		if (ch >= '0' && ch <= '9')
 			return ch - '0';
 		if (ch >= 'A' && ch <= 'F')
 			return ch - 'A' + 10;
 		if (ch >= 'a' && ch <= 'f')
 			return ch - 'a' + 10;

 		throw new IllegalArgumentException("invalid hex digit '" + ch + "'");
 	}
     
     public static SecretKeySpec skeySpec = null;
     
     public static byte[] encryptString(String message) throws Exception{
    	 if(message.length()<1)return null;
    	// Get the KeyGenerator

         KeyGenerator kgen = KeyGenerator.getInstance("AES");
         kgen.init(128); // 192 and 256 bits may not be available


         // Generate the secret key specs.
         SecretKey skey = kgen.generateKey();
         byte[] raw = skey.getEncoded();
         System.out.println(raw);
         System.out.println(asHex((raw)));
         System.out.println(asHex(fromString(asHex(raw))));
         skeySpec = new SecretKeySpec(raw, "AES");
         
         // Instantiate the cipher

         Cipher cipher = Cipher.getInstance("AES");

         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

         byte[] encrypted =
           cipher.doFinal(message.getBytes());
         
    	 return encrypted;
     }
     
     public static String decryptString(byte[] encryptedString) throws Exception{
    	 if(skeySpec==null)return "";
    	 
    	 Cipher cipher = Cipher.getInstance("AES");
    	 
         cipher.init(Cipher.DECRYPT_MODE, skeySpec);
         
         byte[] original = cipher.doFinal(encryptedString);
         
         
         return new String(original);
     }

     public static void main(String[] args) throws Exception{

       String message="changdoc";
       
       byte[] b =encryptString(message);
       String encrypted = asHex(b);
       System.out.println(new String(b));
       System.out.println(encrypted);
       System.out.println(decryptString(b));
     }
       
   }
